package com.study.example.study.extension.caffeinecache;

import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * channel 缓存
 *
 * @author RenYuLiang
 */
@Slf4j
@Component
public class CaffeineCache {

    /**
     * Caffeine Cache 缓存 key
     */
    public static final String CAFFEINE_CACHE_KEY = "ELE_CAFFEINE_CACHE_CHANNEL_KEY";


    /**
     * 创建缓存任务
     */
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void creatCacheTask() {
        // 建的时候就开始计时
        Stopwatch stopwatch = Stopwatch.createStarted();
        log.info("数据放入缓存开始");
        // 模拟数据
        List<String> list = this.listStrings();
        // 创建缓存数据
        CaffeineCacheDTO dto = this.createCache(list);
        // 放入 Caffeine Cache
        this.caffeineCache(dto);
        // 停止计时，然后计算时长.单位为毫秒
        long elapsed = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS);
        log.info("数据放入缓存结束,耗时(毫秒)={}", elapsed);
    }

    /**
     * 模拟数据
     *
     * @return List
     */
    public List<String> listStrings() {
        return Lists.newArrayList("1", "2", "3", "4", "5");
    }

    /**
     * 放入 Caffeine Cache
     *
     * @param dto CaffeineCacheDTO
     */
    public void caffeineCache(final CaffeineCacheDTO dto) {
        if (Objects.isNull(dto)) {
            log.error("缓存放入Caffeine Cache失败，CaffeineCacheDTO为空");
            return;
        }
        StringCaffeineCache.putCache(CAFFEINE_CACHE_KEY, dto);
    }


    /**
     * 创建缓存数据
     *
     * @param list 模拟数据
     * @return CaffeineCacheDTO
     */
    private CaffeineCacheDTO createCache(List<String> list) {
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        CaffeineCacheDTO dto = new CaffeineCacheDTO();
        dto.setStringList(list);
        return dto;
    }


}
